//
//  NXSeventhStepViewController.m
//  BiologyLibrary
//
//  Created by milo on 16/7/5.
//  Copyright © 2016年 youxh. All rights reserved.
//

#import "NXSeventhStepViewController.h"
#import "NXEighthViewController.h"
@interface NXSeventhStepViewController ()

@end

@implementation NXSeventhStepViewController

static const NSString * KEY_STEP  = @"step7";


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _currentStep = self.NewRecordArray.firstObject.savedStepCount + 1;
    _keyStepStr = [NSString stringWithFormat:@"step%ld", _currentStep];
    NSLog(@"setp%ld record === %@", _currentStep, self.NewRecordArray.firstObject.getDetailDict);
    
    [self setNaviBarTitle:self.NewRecordArray.firstObject.name];
    _contentTableView = [[UITableView alloc] initWithFrame:
                         CGRectMake(10, fHeight_Nav + fHeight_StatueBar + 10, fWidth_Current - 20, fHeight_Current - fHeight_Nav + fHeight_StatueBar - 60)];
    _contentTableView.backgroundColor = [UIColor clearColor];
    _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _contentTableView.dataSource = self;
    _contentTableView.delegate = self;
    [self.view addSubview:_contentTableView];
    
    UIImageView*buttomview = [[UIImageView alloc]initWithFrame:CGRectMake(0, fHeight_Current - 50, fWidth_Current, 50)];
    buttomview.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    [self.view addSubview:buttomview];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 50)];
    label.backgroundColor=[UIColor clearColor];
    label.textAlignment=1;
    label.font=[UIFont systemFontOfSize:14];
    label.textColor=[UIColor lightGrayColor];
    label.text= [NSString stringWithFormat:@"当下是第%ld/%ld步",
                 (long)self.NewRecordArray.firstObject.savedStepCount + 1, (long)self.NewRecordArray.firstObject.allStepCount];
    [buttomview addSubview:label];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;//返回标题数组中元素的个数来确定分区的个数
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        NSString*titlestr=@"7.2、石蜡包埋组织样本置入福尔马林时间";
        CGSize hight=[TGCDataCenter getContentSize:titlestr WithMaxSize:CGSizeMake(fWidth_Current-40, 1000) Font:[UIFont systemFontOfSize:17] LineBreakMode:NSLineBreakByWordWrapping];
        return 40+hight.height+60;
    }else{
        return 120.0f;

    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *strIdentifier = [NSString stringWithFormat:@"strIdentifier%ld",(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:strIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
        
        
        
        UILabel *titlelab = [[UILabel alloc]initWithFrame:
                             CGRectMake(10, 0, fWidth_Current - 40, 60)];
        titlelab.textColor=[UIColor whiteColor];
        titlelab.backgroundColor=[UIColor clearColor];
        [cell addSubview:titlelab];
        
        UIImageView*lineview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 60, fWidth_Current-20, 1)];
        lineview.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:0.3];
        [cell addSubview:lineview];
        
        UILabel *dateLabel = [[UILabel alloc]initWithFrame:
                              CGRectMake(10, 60, tableView.frame.size.width - 40, 60)];
        dateLabel.backgroundColor = [UIColor clearColor];
        dateLabel.textColor = [UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
        [cell addSubview:dateLabel];
        
        UIImageView *detailImageView = [[UIImageView alloc] initWithFrame:
                                        CGRectMake(dateLabel.frame.origin.x + dateLabel.frame.size.width,
                                                   dateLabel.frame.origin.y + (dateLabel.frame.size.height - 12) / 2 ,
                                                   12, 12)];
        detailImageView.image = [UIImage imageNamed:@"navleft"];
        [cell addSubview:detailImageView];
        
        if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
            detailImageView.hidden = YES;
        }else{
            detailImageView.hidden = NO;
        }
        
        if(indexPath.section == 0){
            if (self.NewRecordArray.firstObject.type==2) {
                titlelab.text=@"6.1、冻存组织样本置入液氮时间";

            }else{
                titlelab.text=@"7.1、冻存组织样本置入液氮时间";

            }
            UIButton *btn1=[[UIButton alloc]initWithFrame:CGRectMake(fWidth_Current-20-60, 78, 50, 25)];
            btn1.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn1.layer.cornerRadius=10;
            [btn1 setTitle:@"刷新" forState:UIControlStateNormal];
            [btn1 addTarget:self action:@selector(reloadtime1) forControlEvents:UIControlEventTouchUpInside];
            btn1.titleLabel.font=[UIFont systemFontOfSize:11];
            btn1.clipsToBounds=YES;
            [cell addSubview:btn1];

            if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                btn1.hidden = YES;
            }else{
                btn1.hidden = NO;
            }
            
            _date1Label = dateLabel;
            if ([[self.NewRecordArray.firstObject getDetailDict] objectForKey:KEY_STEP] &&
                [[[self.NewRecordArray.firstObject getDetailDict] objectForKey:KEY_STEP] count] > indexPath.section &&
                [[[[self.NewRecordArray.firstObject getDetailDict] objectForKey:KEY_STEP] objectAtIndex:indexPath.section] objectForKey:KEY_RECORD_ANSWER]) {
                
                _date1Label.text = [[[[self.NewRecordArray.firstObject getDetailDict] objectForKey:KEY_STEP] objectAtIndex:indexPath.section] objectForKey:KEY_RECORD_ANSWER];
            }
        }else if (indexPath.section == 1){
            NSString*titlestr=@"7.2、石蜡包埋组织样本置入福尔马林时间";
            CGSize hight=[TGCDataCenter getContentSize:titlestr WithMaxSize:CGSizeMake(fWidth_Current-40, 1000) Font:[UIFont systemFontOfSize:17] LineBreakMode:NSLineBreakByWordWrapping];
            titlelab.frame=CGRectMake(10, 20, fWidth_Current - 40, hight.height);
            if (self.NewRecordArray.firstObject.type==2) {
                titlelab.text=@"6.2、石蜡包埋组织样本置入福尔马林时间";

            }else{
                titlelab.text=@"7.2、石蜡包埋组织样本置入福尔马林时间";

            }
            titlelab.numberOfLines=0;
            _date2Label = dateLabel;
            lineview.frame=CGRectMake(0, hight.height+40, fWidth_Current-20, 1);
            dateLabel.frame=CGRectMake(10, hight.height+40, tableView.frame.size.width - 40, 60);
            detailImageView.frame=CGRectMake(dateLabel.frame.origin.x + dateLabel.frame.size.width,
                                          dateLabel.frame.origin.y + (dateLabel.frame.size.height - 12) / 2 ,
                                          12, 12);
            UIButton *btn1=[[UIButton alloc]initWithFrame:CGRectMake(fWidth_Current-20-60, hight.height+40+18, 50, 25)];
            btn1.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn1.layer.cornerRadius=10;
            [btn1 setTitle:@"刷新" forState:UIControlStateNormal];
            [btn1 addTarget:self action:@selector(reloadtime2) forControlEvents:UIControlEventTouchUpInside];
            btn1.titleLabel.font=[UIFont systemFontOfSize:11];
            btn1.clipsToBounds=YES;
            [cell addSubview:btn1];

            if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                btn1.hidden = YES;
            }else{
                btn1.hidden = NO;
            }
        
            if ([[self.NewRecordArray.firstObject getDetailDict] objectForKey:KEY_STEP] &&
                [[[self.NewRecordArray.firstObject getDetailDict] objectForKey:KEY_STEP] count] > indexPath.section &&
                [[[[self.NewRecordArray.firstObject getDetailDict] objectForKey:KEY_STEP] objectAtIndex:indexPath.section] objectForKey:KEY_RECORD_ANSWER]) {
                
                _date2Label.text = [[[[self.NewRecordArray.firstObject getDetailDict] objectForKey:KEY_STEP] objectAtIndex:indexPath.section] objectForKey:KEY_RECORD_ANSWER];
            }
        }
        
    }
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==1) {
        return 70.0f;
        
    }else{
        return 10;
    }
}

- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    if (section==1) {
        UIView *footerView = [[UIView alloc] initWithFrame:
                              CGRectMake(0, 0, tableView.frame.size.width , 50)];
        footerView.backgroundColor = [UIColor clearColor];
        
        if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
            
            UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake(0, 10, footerView.frame.size.width, 50)];
            btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn2.layer.cornerRadius=5;
            [btn2 setTitle:@"下一步" forState:UIControlStateNormal];
            btn2.clipsToBounds=YES;
            [btn2 addTarget:self action:@selector(nextStepClick) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:btn2];
            return footerView;
        }else{
            UIButton *btn1=[[UIButton alloc]initWithFrame:
                            CGRectMake(0, 10, (footerView.frame.size.width - 10) / 2, 50)];
            btn1.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
            btn1.layer.cornerRadius=5;
            [btn1 setTitle:@"取消" forState:UIControlStateNormal];
            btn1.clipsToBounds=YES;
            [btn1 addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:btn1];
            UIButton *btn2=[[UIButton alloc]initWithFrame:
                            CGRectMake(btn1.frame.origin.x + btn1.frame.size.width + 10,
                                       btn1.frame.origin.y,
                                       btn1.frame.size.width, btn1.frame.size.height)];
            btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn2.layer.cornerRadius=5;
            [btn2 setTitle:@"保存" forState:UIControlStateNormal];
            btn2.clipsToBounds=YES;
            [btn2 addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:btn2];
            
            return footerView;
        }
    }else{
        UIView *footerView = [[UIView alloc] initWithFrame:
                              CGRectMake(0, 0, tableView.frame.size.width , 10)];
        footerView.backgroundColor = [UIColor clearColor];
        return footerView;
    }
    
}
-(void)reloadtime1{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    _date1Label.text=dateString;
}
-(void)reloadtime2{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    _date2Label.text=dateString;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    _selectedIndex = indexPath.section;
    
//    if (!_datePickAlertVC) {
//        _datePickAlertVC = [UIAlertController alertControllerWithTitle:@"" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];
//        //初始化一个标题为“选择时间”，风格是ActionSheet的UIAlertController，其中"\n"是为了给DatePicker腾出空间
//        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//            //点击确定按钮的事件处理
//            if(_selectedIndex == 0){
//                _date1Label.text = [self dateToString:_datePicker.date];
//            }else if(_selectedIndex == 1){
//                _date2Label.text = [self dateToString:_datePicker.date];
//            }
//        }];
//        
//        _datePicker = [[UIDatePicker alloc] init];//初始化一个UIDatePicker
//        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
//        [_datePickAlertVC.view addSubview:_datePicker];//将datePicker添加到UIAlertController实例中
//        [_datePickAlertVC addAction:cancel];//将确定按钮添加到UIAlertController实例中
//    }
//    [self presentViewController:_datePickAlertVC animated:YES completion:^{
//    }];//通过模态视图模式显示UIAlertController，相当于UIACtionSheet的show方法
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)saveClick{
    if(_date1Label.text == nil || [_date1Label.text isEqualToString:@""]){
        [self.view makeToast:@"请选择冻存组织样本置入液氮时间！"];
        return;
    }
    
    if(_date2Label.text == nil || [_date2Label.text isEqualToString:@""]){
        [self.view makeToast:@"请选择石蜡包埋组织样本置入福尔马林时间！"];
        return;
    }
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
    [formatter2 setDateFormat:@"yyyy-MM-dd hh:mm"];
    NSDate *date11=[formatter2 dateFromString:_date1Label.text];
    NSDate *date22=[formatter2 dateFromString:_date2Label.text];
    NSTimeInterval secondsInterval2= [date22 timeIntervalSinceDate:date11];
    
    if (secondsInterval2<0) {
        [self.view makeToast:@"抱歉，置入福尔马林时间不能小于样本置入液氮时间"];
        return;
    }
    for (Record *model in self.NewRecordArray) {
        [self creatDetailDict:model];
        model.savedStepCount = _currentStep;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [model update];
        });
    }
    
    NSMutableArray *types = [NSMutableArray arrayWithCapacity:0];
    for (Record *model in self.NewRecordArray) {
        NSString*step3date = [[[[model getDetailDict] objectForKey:@"step3"] objectAtIndex:1] objectForKey:KEY_RECORD_ANSWER];
        NSString*step7date = [[[[model getDetailDict] objectForKey:@"step7"] objectAtIndex:1] objectForKey:KEY_RECORD_ANSWER];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
        NSDate *date1=[formatter dateFromString:step3date];
        NSDate *date2=[formatter dateFromString:step7date];
        NSTimeInterval secondsInterval= [date2 timeIntervalSinceDate:date1];
        NSString *type=@"";
        if (secondsInterval>1200) {
            type =@"1";
        }else {
            type =@"0";
            
        }
        [types addObject:type];
    }
    

    NXEighthViewController *NXEighthStepVC = [[NXEighthViewController alloc] init];
    NXEighthStepVC.NewRecordArray = self.NewRecordArray;
    NXEighthStepVC.types = types;
    [self.navigationController pushViewController:NXEighthStepVC animated:YES];
}

- (NSString *)dateToString:(NSDate *)date {
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT+0800"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    
    [formatter setTimeZone:timeZone];
    
    NSString * timeString = [formatter stringFromDate:date];
    
    return timeString;
}

-(void)creatDetailDict:(Record *)model{
    
    NSDictionary *question1Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   @"7.1、冻存组织样本置入液氮时间", KEY_RECORD_QUESTION,
                                   TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                   _date1Label.text, KEY_RECORD_ANSWER, nil];
    NSDictionary *question2Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   @"7.2、石蜡包埋组织样本置入福尔马林时间", KEY_RECORD_QUESTION,
                                   TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                   _date2Label.text, KEY_RECORD_ANSWER, nil];
    
    NSArray *qustionArr = [NSArray arrayWithObjects:question1Dict, question2Dict, nil];
    
    NSMutableDictionary *tempDict = [model getDetailDict];
    [tempDict setObject:qustionArr forKey:KEY_STEP];
    [model setDetailDict:tempDict];
    model.recordDetail = [tempDict JSONString];
}
-(void)cancelclick{
    UIViewController*miloViewControl=(UIViewController *)[[self.navigationController viewControllers]objectAtIndex:1];
    [self.navigationController popToViewController:miloViewControl animated:YES];
}

-(void)nextStepClick{
    for (Record *model in self.NewRecordArray) {
        model.savedStepCount = _currentStep;
    }
    NSMutableArray *types = [NSMutableArray arrayWithCapacity:0];
    for (Record *model in self.NewRecordArray) {
        NSString*step3date = [[[[model getDetailDict] objectForKey:@"step3"] objectAtIndex:1] objectForKey:KEY_RECORD_ANSWER];
        NSString*step7date = [[[[model getDetailDict] objectForKey:@"step7"] objectAtIndex:1] objectForKey:KEY_RECORD_ANSWER];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
        NSDate *date1=[formatter dateFromString:step3date];
        NSDate *date2=[formatter dateFromString:step7date];
        NSTimeInterval secondsInterval= [date2 timeIntervalSinceDate:date1];
        NSString *type=@"";
        if (secondsInterval>1200) {
            type =@"1";
        }else {
            type =@"0";
            
        }
        [types addObject:type];
    }
    NXEighthViewController *NXEighthStepVC = [[NXEighthViewController alloc] init];
    NXEighthStepVC.NewRecordArray = self.NewRecordArray;
    NXEighthStepVC.fromtype = @"search";
    NXEighthStepVC.types = types;
    [self.navigationController pushViewController:NXEighthStepVC animated:YES];
}

@end

